package com.luobi.rabbitmq.filter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

import static com.luobi.rabbitmq.constants.TraceIdConstants.CONTEXT_TRACE_ID;
import static com.luobi.rabbitmq.constants.TraceIdConstants.TRACE_ID_HEADER_KEY;
import static com.luobi.rabbitmq.constants.TraceIdConstants.USER_REQ_ID_HEADER_KEY;

@WebFilter
public class LogbackFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        String traceId = httpServletRequest.getHeader(USER_REQ_ID_HEADER_KEY);  // 获取请求头中的requestId
        if (StringUtils.isBlank(traceId)) {
            traceId = StringUtils.replace(UUID.randomUUID().toString(), "-", "");
        }

        ((HttpServletResponse) response).setHeader(TRACE_ID_HEADER_KEY, traceId);  // 设置响应头中的traceId

        MDC.put(CONTEXT_TRACE_ID, traceId);  // 将traceId放入MDC中，可以全局获取，方法：MDC.get(CONTEXT_TRACE_ID)

        chain.doFilter(request, response);
    }

}
